<template>
      <div class="fd-charts"   :id="scope.id" ></div>
</template>

<script>
import $ from "jquery";
const echarts = require("echarts");
export default {
  name: "drawCharts",
  props: {
    options: {
      type: Object,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    clickCallback: {
      type: Function
    }
  },
  data () {
    return {
      scope: {
        options: this.options,
        id: this.id,
        clickCallback: this.clickCallback
      }
    };
  },
  watch: {
    options: {
      deep: true,
      handler: function () {
        this.update(this);
      }
    }
  },
  // 插入到真实dom后
  mounted: function () {
    // 初始化
    this.init();
  },
  methods: {
    // 更新图表
    update: function (_this) {
      // 生成图表
      this.$nextTick(() => {
        _this.myChart.clear();
        _this.myChart.setOption(_this.options);
      });
    },
    // 销毁图表
    destory: function () {
      const _this = this;
      $(window).off("resize." + _this.scope.id);
      _this.myChart.clear();
      _this.myChart.dispose();
    },
    // 绑定事件
    bindEvent: function () {
      const _this = this;
      // 绑定resize事件
      $(window).off("resize." + _this.scope.id)
        .on("resize." + _this.scope.id, function () {
          _this.myChart.resize();
        });
    },
    // 创建图表
    createChart: function () {
      const _this = this;
      // 生成图表实例
      _this.myChart = echarts.init(document.getElementById(_this.scope.id));
      // 生成图表
      _this.myChart.setOption(_this.scope.options);

      /* 绑定事件*/
      if (_this.scope.clickCallback) {
        _this.myChart.on("click", function (param) {
          _this.scope.clickCallback(param);
        });
      }
    },
    // 初始化函数
    init: function () {
      const _this = this;
      // 创建图表
      _this.createChart();
      // 绑定事件
      _this.bindEvent();
    }
  },
  beforeDestroy () {
    this.destory();
  }
};
</script>

<style scoped>

</style>
